package com.elite.groovy.callback
import com.elite.groovy.kh.DHAESUtil
import com.elite.groovy.kh.getProperty;
import com.elite.groovy.util.EliteBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.elite.groovy.util.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import java.security.MessageDigest;

/**
 * @use 续保外呼，获取预期赔付率
 * @author admin
 *
 */

public class GetExpectInfo implements ServiceBackInvoke{
    private static final Log log=LogFactory.getLog(GetExpectInfo.class);
    private String charset = "utf-8"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 0;
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {


        try {
			log.debug("续保获取预期赔付率------开始------");


            def mapn = "";
            def voctable = eliteBean.chaxun_sql("select c.RELATION_ID, (case when c.receipor is not null and c.receipor <>'null' then c.receipor else c.handlercode end) userCode , c.frameno frameNo,c.policyNo policyno from XB_CUST_CASE c where to_char(c.create_date,'yyyy-mm-dd') = to_char(sysdate,'yyyy-mm-dd')  and (c.goodsid<>'1' or c.goodsid is null) and rownum<51", "dataSource");


			//接口参数
            def querySql = "select t.url, t.edj_appkey, t.edj_efrom,t.edj_secret from SYSC_INTERFACE t where t.urltype='getExpect'";
            def quelist = eliteBean.chaxun_sql(querySql, "dataSource");
            def map3 = quelist[0];
            def url = map3.get("url");
            def appId = map3.get("edj_appkey");
            def fromType = map3.get("edj_efrom");
			def projectId = map3.get("edj_secret");

			log.debug("url:"+url);

			def qSql = "select parametervalue from sysc_parameter where parameter_id='DEBAES'";
            def qlist = eliteBean.chaxun_sql(qSql, "dataSource");
            def mapq = qlist[0];
			def DEBAES = mapq.get("parametervalue");

			Long timestamp1 = System.currentTimeMillis();


            if (voctable != null && voctable.size() > 0) {
                for (def i = 0; i < voctable.size(); i++) {
                    mapn = voctable[i];
                    def RELATION_ID = mapn.get("RELATION_ID");
                    def userCode = mapn.get("userCode");  //业务员
                    def frameNo = mapn.get("frameNo");  //车架号
                    def policyNo = mapn.get("policyNo");  //保单号


					//reqData加密 AES算法
					String reqData = "{\"userCode\": \""+userCode+"\",\"frameNo\": \""+frameNo+"\",\"policyNo\": \""+policyNo+"\"}" 

					log.debug("加密前reqData:"+reqData);
					def assertKey = getProperty.get("ZhanYeAESPassword");
					def reqDataAES= DHAESUtil.encrypt(reqData,assertKey);
					log.debug("加密后reqData:"+reqDataAES);

					//sign加密 SHA256算法
					String sign = "appId="+appId+"fromType="+fromType+"projectId="+projectId+"reqData="+reqDataAES+"timestamp="+String.valueOf(timestamp1)+DEBAES;
					log.debug("加密前sign:"+sign);
					//创建SHA-256哈希算法的MessageDigest对象
					MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
					//使用SHA-256计算字符串的哈希值
					byte[] hash = sha256.digest(sign.getBytes("UTF-8"));
					//将字节转换为十六进制字符串
					StringBuilder hexString = new StringBuilder();
					for (byte b : hash) {
						String hex = Integer.toHexString(0xff & b);
						if (hex.length() == 1) {
							hexString.append('0');
						}
						hexString.append(hex);
					}
					String signSHA256 = hexString.toString();
					log.debug("加密后sign:"+signSHA256);

					//拼接参数
					String rd = "{\"appId\":\""+appId+"\",\"fromType\":\""+fromType+"\",\"projectId\":\""+projectId+"\",\"timestamp\":\""+timestamp1+"\",\"reqData\":\""+reqDataAES+"\",\"sign\":\""+signSHA256+"\"}"

					//请求接口
					Map headMap=new HashMap(); //设置头文件
					headMap.put("Content-Type","application/json");

					try{
						def msgjson = Util.doHttpPostUseHead(url,rd,charset,timeout,enableSSLflag,headMap);
						log.debug(msgjson);
						JSONObject obj = JSONObject.fromObject(msgjson);
						def code=obj.get("code");
						def msg=obj.get("msg");

						if(code!= 1&&!"1".equals(code)){
							eliteBean.update("update xb_cust_case set goodsid ='1',planname ='"+msg+"' where relation_id = '"+RELATION_ID+"'","dataSource");
						}else{
							
							//解密返回参数
							def resDataAes=DHAESUtil.decrypt(msg,assertKey);
							log.debug("resDataAes:"+resDataAes);
							JSONObject resObj = JSONObject.fromObject(resDataAes);
							def bInfo =resObj.get("BiapQtnBillInfo");
							JSONObject infoJson = JSONObject.fromObject(bInfo);
							def billELR = infoJson.get("BillELR");
							if(billELR !="" && billELR != null && !"null".equals(billELR)){
								eliteBean.update("update xb_cust_case set goodsid ='1' ,goodsname='"+billELR+"' where relation_id = '"+RELATION_ID+"'","dataSource");
							}else{
								def lrCoExpectLossRatio = infoJson.get("LrCoExpectLossRatio");
								eliteBean.update("update xb_cust_case set goodsid ='1' ,goodsname='"+lrCoExpectLossRatio+"' where relation_id = '"+RELATION_ID+"'","dataSource");
							}
						}
					}catch(Exception e){
						log.debug(e);
					}	


                }
            }
			log.debug("----------GetPolicyInfo(续保外呼，获取上年保单信息)完成----------");
			
        }catch(Exception e){
            log.debug("----------GetPolicyInfo(续保外呼，获取上年保单信息)异常----------");
            log.error("" ,e);
        }

		return "1";
    }

}
